<template>
  <div>
    <!--搜索框-->
    <div
      @click.stop="handleSearchClick"
      @contextmenu.stop="handleSearchClick"
      id="search-bar"
      class="transition"
      :class="{active: useStore.isSearchMode}"
    >
      <SearchBarMenu>
        <div :class="{hidden: !useStore.isSearchMode}" class="search-left transition">
          <div class="icon">
            <i class="iconfont" :class="useMenu.activatedEngine.icon"></i>
          </div>
        </div>
      </SearchBarMenu>
      <div class="search-text">
        <!--@input="refreshSuggestion"-->
        <input
            ref="searchRef"
            v-model="useMenu.searchContent"
            :placeholder="useMenu.searchPlaceholder"
            class="search-input transition"
            :class="{active: useStore.isSearchMode}"
            type="text"
            @keydown.enter="openSearchPage"
            @keydown="handleSearchInputKeydown"
        />
      </div>
      <div :class="{hidden: !useStore.isSearchMode}" class="search-right transition" @click="openSearchPage">
        <svg v-show="useStore.isSearchMode" aria-hidden="true" class="icon">
          <use xlink:href="#icon-sousuo1-copy"></use>
        </svg>
      </div>
    </div>
    <!--搜索结果-->
    <div v-if="useMenu.searchContent && useStore.isSearchMode" class="search-result" @click.stop>
      <div v-show="!searchResults" class="loading"></div>
      <ul v-show="searchResults">
        <li class="search-result-item transition" v-if="useStore.searchResultsOption === '历史记录'">
          <a @click="handleHistory">
            <svg aria-hidden="true" class="icon">
              <use xlink:href="#icon-lishijilu1"></use>
            </svg>
            搜索历史记录
          </a>
        </li>
        <li class="search-result-item transition" v-else>
          <a @click="handleTranslate">
            <svg aria-hidden="true" class="icon">
              <use xlink:href="#icon-yuyanfanyi"></use>
            </svg>
            翻译：{{useMenu.searchContent}}
          </a>
        </li>
        <li v-for="(item, index) in searchResults" :key="item" @click="handleSearchContent(item)" class="search-result-item transition" :class="{active: index === useStore.currentSelectedSearchResultIndex}">
          <a :href="`${useMenu.activatedEngine.url}${item}`" target="_blank">
            {{item}}
          </a>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import SearchBarMenu from "./SearchBarMenu.vue";
import jsonp from "jsonp";
import {debounce} from "@/toolsjs/debounce";
import {ref, onMounted} from "vue";
import {storeToRefs} from "pinia";
import {useHomeStore} from "@/stores/home";
import {useMenuStore} from "@/stores/menu";

const useMenu = useMenuStore();
const useStore = useHomeStore();
const {searchResults} = storeToRefs(useStore);

const searchRef = ref()

// 必应请求搜索返回的接口函数
function bing() {
  //组装查询地址
  // https://api.bing.com/qsonhs.aspx?type=cb&q=前端&cb=window.bing.sug
  const sugUrl = `https://api.bing.com/qsonhs.aspx?type=cb&q=${useMenu.searchContent}&cb=window.baidu.sug`;
  //定义回调函数
  let arr = [];
  window.baidu = {
    sug: function (json) {
      json?.AS?.Results?.forEach((item) => {
        item.Suggests.forEach((res) => {
          // console.log("1", res.Txt);
          arr.push(res.Txt);
        });
      });
    },
  };
  //动态添加JS脚本
  const script = document.createElement("script");
  script.src = sugUrl;
  document.getElementsByTagName("head")[0].appendChild(script);
  return arr;
}
// 跳转时把点击搜索结果列内容添加到历史搜索列表里
const handleSearchContent = (item)=>{
  // console.log(item);
  if(useStore.Traceless){
    useStore.Historys = []
  }else{
    useStore.Historys.push({
    id:useStore.Historys.length+1,
    content:item,
    create_time:new Date().toLocaleString()
    })
  }
}
const refreshSuggestion = debounce(() => {
  if (useMenu.searchContent !== "")
    // obj.List = bing()
    // console.log(bing());
    // jsonp(`https://api.bing.com/qsonhs.aspx?type=cb&q=${useMenu.searchContent}`, null);
    jsonp(`https://suggestion.baidu.com/su?wd=${useMenu.searchContent}`, null, null);
}, 250);

/**
 * 当按下 回车键 / 点击搜索按钮 时，根据 pinia 中选中的搜索引擎，打开相应的搜索页面
 */
function openSearchPage() {
  if (useMenu.searchContent !== "") {
    window.open(
        `${useMenu.activatedEngine.url}${useMenu.searchContent}`,
        useMenu.target_blank ? "_blank" : "_self"
    )
    // console.log(useStore.Historys.length);
  if(useStore.Traceless){
    useStore.Historys = []
  }else{
     useStore.Historys.push({
      id:useStore.Historys.length+1,
      content:useMenu.searchContent,
      create_time:new Date().toLocaleString()
      })
  }
   
    // console.log(useStore.Historys.length+1);
    useMenu.searchContent = ""
    searchRef.value.focus()
    useStore.searchResults = null;
    
  }
}

const handleHistory = ()=>{
  useStore.isHistorySearch = true
}

const handleTranslate = ()=>{
  window.open(
        `https://fanyi.baidu.com/?aldtype=16047#zh/en/${useMenu.searchContent}`,
        useMenu.target_blank ? "_blank" : "_self"
    )
}

/**
 * 当从「网址捷径」切换回「搜索栏」时，若之前选中了「搜索栏」，自动重新聚焦
 */
onMounted(() => {
  if (useStore.isSearchMode) {
    searchRef.value.focus()
  }
})

/**
 * 点击搜索框事件
 */
const handleSearchClick = () => {
  useStore.isMask = true
  useStore.isSearchMode = true
  searchRef.value.focus()
}

/**
 * 根据上下方向键切换搜索结果
 * @param e
 */
const handleSearchInputKeydown = e => {
  // if (useStore.searchContent !== '') {
  //   useStore.searchResults = null;
  // }
  switch (e.code) {
    case 'ArrowUp':
      e.preventDefault()
      if (useStore.currentSelectedSearchResultIndex === -1 || useStore.currentSelectedSearchResultIndex === 0) {
        useStore.currentSelectedSearchResultIndex = useStore.searchResults.length - 1
      } else {
        useStore.currentSelectedSearchResultIndex--
      }
      useMenu.searchContent = useStore.searchResults[useStore.currentSelectedSearchResultIndex]
      break
    case 'ArrowDown':
      e.preventDefault()
      if (useStore.currentSelectedSearchResultIndex === -1 || useStore.currentSelectedSearchResultIndex === useStore.searchResults.length - 1) {
        useStore.currentSelectedSearchResultIndex = 0
      } else {
        useStore.currentSelectedSearchResultIndex++
      }
      useMenu.searchContent = useStore.searchResults[useStore.currentSelectedSearchResultIndex]
      break
    default:
      refreshSuggestion()
  }
}
</script>

<style lang="less" scoped>
#search-bar {
  margin: 10px auto 0;
  cursor: pointer;
  border-radius: 20px;
  padding: 0 10px;
  width: min(300px, 65%);
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  backdrop-filter: blur(8px);
  background-color: rgba(255, 255, 255, 0.25);
  box-shadow: rgb(0 0 0 / 20%) 0 0 10px;
  box-sizing: border-box;
  position: relative;
  z-index: 10;

  &:not(.active) .search-input {
    color: #ffffff91;
  }

  &:hover {
    width: min(460px, 80%);
  }

  &.active {
    cursor: text;
    width: min(460px, 80%) !important;
    background-color: #eaebec !important;
  }

  .search-text {
    width: 100%;
    height: 30px;
    line-height: 30px;

    .search-input {
      cursor: inherit;
      border: 0;
      width: 100%;
      height: 100%;
      text-align: center;
      background-color: transparent;

      &::placeholder {
        transition: 250ms;
        color: #ffffff91;
      }

      &.active::placeholder {
        color: black;
      }
    }
  }

  .icon {
    width: 18px;
    height: 18px;
  }

  .search-left, .search-right {
    transform: scale(.85);
    cursor: pointer;
    border-radius: 50%;
    width: 44px;
    height: 36px;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
      background-color: white;
    }

    &.hidden {
      opacity: 0;
      pointer-events: none;
    }

    .icon {
      width: 22px;
      height: 22px;
      text-align: center;
      line-height: 22px;

      i {
        font-size: 22px;
      }
    }
  }

  .search-bar-menu {
    position: absolute;
    left: 0;
    top: 42px;
  }
}

.search-result {
  position: relative;
  margin: .5rem auto 0;
  width: min(460px, 80%);
  min-height: 160px;
  padding: .5rem 1rem;
  box-sizing: border-box;
  border-radius: 20px;
  color: black;
  background-color: rgba(255, 255, 255, .75);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: normal;

  .loading {
    position: absolute;
    top: calc(80px - 1.75rem);
    left: calc(50% - 1.75em);
    display: flex;
    width: 3.5em;
    height: 3.5em;
    border: 3px solid transparent;
    border-top-color: #000;
    border-bottom-color: #000;
    border-radius: 50%;
    animation: spin 1.5s linear infinite;
  }

  .loading:before {
    content: "";
    display: block;
    margin: auto;
    width: 0.75em;
    height: 0.75em;
    border: 3px solid #000;
    border-radius: 50%;
    animation: pulse .5s alternate ease-in-out infinite;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }

  @keyframes pulse {
    from {
      transform: scale(0.5);
    }
    to {
      transform: scale(1);
    }
  }

  .search-result-item {
    cursor: pointer;
    box-sizing: border-box;
    width: 100%;
    height: 26px;
    line-height: 26px;
    font-size: 15px;

    a {
      display: block;
      padding: 0 1rem;
    }

    &:hover, &.active {
      border-radius: 4px;
      background-color: rgba(255, 255, 255, 1);
    }

    &:first-child {
      height: 32px;

      a {
        height: 100%;
        display: flex;
        align-items: center;
      }

      .icon {
        width: 26px;
        height: 26px;
        margin-right: .5rem;
      }
    }
  }
}
</style>